package com.example.demo;

import java.util.HashMap;
import java.util.Map;

/**
 * 两数之和
 *
 * @author chenye
 */
public class LeetCode01 {

    /**
     * 方式一 暴力法，
     */
    public static void twoSum(int[] numbers, int targert) {
        int numberslength = numbers.length;
        Map map = new HashMap<>(numberslength);
        for (int i = 0; i < numberslength; i++) {
            map.put(numbers[i], i);
        }
        for (int i = 0; i < numberslength; i++) {
            int complement = targert - numbers[i];
            if (map.containsKey(complement)) {
                System.out.println(i + "," + map.get(complement));
                map.remove(numbers[i]);
            }
        }
    }

    /**
     * 方法二，两边哈希法
     */
    public static int[] twoSun2(int[] nums, int target) {
        Map map = new HashMap();
        Integer len = nums.length;
        for (int i = 0; i < len; i++) {
            map.put(nums[i], i);
        }
        for (int j = 0; j < len; j++) {
            Integer difference = target - nums[j];
            if (map.containsKey(difference)) {
                return new int[]
                        {
                                difference
                                        , nums[j]
                        };
            }
        }
        return null;
    }

    public static void main(String[] args) {
        //twoSum(new int[]{1, 2, 3, 4, 5, 6}, 7);
        System.out.println(twoSun2(new int[]{1, 2, 3, 4, 5, 6}, 7));
    }
}
